<template>
  <el-dialog
    :visible.sync="show"
    width="500px"
    :append-to-body="true"
    :close-on-click-modal="false"
    :show-close="false"
  >
    <div slot="title" class="title_close">
      <!-- 佣金计算器 -->
      <div class="title">{{$t('account_dialog.calculation_dialog.56hr016ncos0')}}</div>
      <img
        src="@/assets/img/icon_gb1.png"
        class="close"
        @click="hideCommission"
      />
    </div>
    <div class="commission_cal" v-if="stockInfo.detail">
      <div class="current_commission">
        <span class="commissionPrice">{{ Number(brokerage).toFixed(2) }}</span>
        <span class="commissionUnit">{{ currency }}</span>
      </div>
      <!-- 股票 -->
      <el-form
        ref="form"
        class="form_cal"
        :model="commissionForm"
        label-width="80px"
      >
        <el-form-item :label="$t('account_dialog.calculation_dialog.56hr016ndz80')">
          <el-autocomplete
            class="search"
            v-model="valur"
            :popper-append-to-body="false"
            :fetch-suggestions="querySearch"
            :placeholder="$t('m.inputStock')"
            :trigger-on-focus="false"
            @select="handleSelect"
            @focus="isHandle"
            clearable
            ref="elautocomplete"
          >
            <img class="inco_seach" src="@/assets/img/icon_ss.png" slot="suffix" />
            <template slot-scope="{ item }">
              <div class="name">{{ item.name }}</div>
              <span class="addr">{{ item.symbol }}({{ item.market | Market }})</span>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item :label="$t('account_dialog.calculation_dialog.56hr016nea40')">
          <!-- 港股价格计步器 -->
          <InputNumber
            v-if="stockInfo.detail.market == 'HKEX'"
            @priceNumber="priceNumber"
            :currenPrice="currenPrice"
          ></InputNumber>
          <!-- 沪深价格计步器 -->
          <el-input-number
            v-else-if="
              stockInfo.detail.market == 'SSE' ||
              stockInfo.detail.market == 'SZSE'
            "
            v-model="currenPrice"
            :step="0.01"
            :precision="2"
            :placeholder="$t('account_dialog.calculation_dialog.56hr016neiw0')"
          ></el-input-number>
          <!-- 美股价格计步器 -->
          <el-input-number
            v-else
            v-model="currenPrice"
            :step="currenPrice >= 1 ? 0.01 : 0.001"
            :precision="currenPrice >= 1 ? 2 : 3"
            :placeholder="$t('account_dialog.calculation_dialog.56hr016neiw0')"
            @change="priceNumber"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('account_dialog.calculation_dialog.56hr016ner80')">
          <el-input-number
            v-model="commissionForm.num"
            :min="0"
            :step="Number(this.stockInfo.detail.lotSize)"
            step-strictly
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('account_dialog.calculation_dialog.56hr016nf080')">
          <el-radio-group v-model="commissionForm.type" @change="changeType">
            <el-radio :label="1">{{$t('account_dialog.calculation_dialog.56hr016nf8s0')}}</el-radio>
            <el-radio :label="2">{{$t('account_dialog.calculation_dialog.56hr016nfh00')}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="computed">
        <button @click="calculation" class="bt-blue">
          {{$t('account_dialog.calculation_dialog.56hr016nfpk0')}}
        </button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import InputNumber from "@/components/common/InputNumber";
import {get_details, get_more} from '@/assets/js/API/market.js';
import { get_common_reckon} from '@/assets/js/API/system.js';
import {post_history, get_search} from '@/assets/js/API/user.js';
export default {
  props: {
    show: Boolean,
  },
  components: {
    InputNumber,
  },
  data() {
    return {
      commissionForm: {
        price: null,
        num: null,
        type: 1,
      },
      valur: "", // 搜索内容
      obj: {}, // 搜索股票内容
      brokerage: 0, //佣金及费用（估算）
      reckonList: {}, //佣金的数值 如0.0029%等
      CloseList: {}, //卖出时使用到的内容 目前只有美股有卖出
      currency: "", // 当前币种
      isSeachHandle: false, // 选择股票
      currenPrice: "0.000", // 当前价格
    };
  },
  created() {},
  mounted() {
    this.lang = localStorage.getItem("lang");
    var lang = localStorage.getItem("lang") == "en" ? "en" : "zh-CN";
  },
  methods: {
    // 获取股票输入焦点
    isHandle() {
      this.isSeachHandle = false;
    },
    hideCommission() {
      this.commissionForm = {
        price: null,
        num: null,
        type: 1,
      },
      this.valur = "";
      this.brokerage = 0;
      this.currency = "";
      this.currenPrice = "0.00";
      this.$emit("close", "calculationShow");
    },
    // 计算佣金
    async calculation() {
      if(!this.valur) return this.$message.error(this.$t('account_dialog.calculation_dialog.56hr016nfy00'));
      if(!this.isSeachHandle) return this.$message.error(this.$t('account_dialog.calculation_dialog.56hr016ng5w0'));
      if(!this.commissionForm.price) return this.$message.error(this.$t('account_dialog.calculation_dialog.56hr016nggo0'));
      if(!this.commissionForm.num) return this.$message.error(this.$t('account_dialog.calculation_dialog.56hr016ngsk0'));
      // 获取佣金信息详情
      await this.reckon(this.obj);
      // 计算佣金
      this.brokerageList(
        this.commissionForm.price,
        this.commissionForm.num,
        this.obj.market,
        this.reckonList,
        this.CloseList
      );
    },// 计步器中的买卖价格变化后触发
    priceNumber(price) {
      // 计步器组件中的变量变化后存储到currenPrice
      this.currenPrice = price.toString();
      // 将当前价格存入买卖提交表单中
      this.commissionForm.price = this.currenPrice;
    },
    // 搜索接口
    async querySearch(queryString, cb) {
      const res = await get_search({
        //搜索接口
        keyword: queryString,
      });
      if (res.code !== 1) return this.$message.error(res.msg);
      this.$refs.elautocomplete.activated = true;
      let results = queryString
        ? res.data.list.filter(this.createFilter(queryString))
        : res.data.list;
      // console.log(results);
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant;
      };
    },
    // 选择搜索股票
    async handleSelect(item) {
      this.obj = {
        securityType: item.securityType,
        symbol: item.symbol,
        market: item.market,
      };
      // this.$store.dispatch("SetStockData", this.obj);
      await this.historyAdd(this.obj);
      await this.getStockInfo(this.obj);
      await this.getStockMore(this.obj);
      this.valur = `${item.name}(${item.symbol})`;
      this.commissionForm.price = this.stockInfo.detail.latestPrice;
      this.currenPrice = (this.stockInfo.detail.latestPrice).toString();
      this.commissionForm.num = this.stockInfo.detail.lotSize;
      this.currency = this.stockInfo.detail.currency=='CNY'?'CNH':this.stockInfo.detail.currency;
    },
    // 获取股票详情
    async getStockInfo(item) {
      var obj = {
        securityType: item.securityType,
        symbol: item.symbol,
        market: item.market,
      };
      const res = await get_details(obj);
      if(res.code != 1) return this.$message.error(res.msg);
      this.$store.dispatch("SetStock",res.data);
      this.isSeachHandle =  true; // 选择股票
    },
    // 获取股票更多信息
    async getStockMore(item) {
      const res = await get_more({
          market: item.market,
          symbol: item.symbol,
          securityType: item.securityType,
        });
      if (res.code != 1) return this.$message.error(res.msg);
      this.$store.dispatch("SetStockMore", res.data.info);
    },
    //  股票搜索历史 GET 获取 POST 插入 /api/search/history
    async historyAdd(item) {
      var obj = {
        securityType: item.securityType,
        symbol: item.symbol,
        market: item.market,
      };
      const res = await post_history(obj);
      if (res.code != 1) return this.$message.error(res.msg);
    },
    changeType(val) {
      console.log(val);
      this.commissionForm.type = val;
    },
    //  佣金计算器 /api/common/reckon
    async reckon(obj) {
      const res = await get_common_reckon(obj);
      if (res.code != 1) return this.$message.error(res.msg);
      if (
        res.data.detail.market.toLowerCase() == "sse" ||
        res.data.detail.market.toLowerCase() == "szse"
      ) {
        this.reckonList = res.data.fee.open.CN;
        this.CloseList = res.data.fee.close.CN;
      } else {
        this.reckonList = res.data.fee.open[res.data.detail.market];
        this.CloseList = res.data.fee.close[res.data.detail.market];
      }
    },
    // 取最大最小值范围内的手续费，isStamp表示是否是印花税，贷款利息
    maxmin(totalPrice, current, max, min, isStamp, isDaily) {
      let currentFee = Number(current * totalPrice);
      // 印花税需向上取整后再做最大最小值判断
      if (isStamp == true) {
        currentFee = Math.ceil(currentFee);
      }
      // 融资日息 = （融资利率 * 贷款金额）/ 365
      if (isDaily == true) {
        currentFee = currentFee / 365;
      }
      if (max == "" || max == null || max == undefined) {
        // 无最大值
        if (min == "" || min == null || min == undefined)
          return Number(currentFee);
        // 无最小
        else return Number(currentFee <= min ? min : currentFee); // 无最大有最小
      } else {
        // 有最大值,无最小
        if (min == "" || min == null || min == undefined)
          return Number(currentFee >= max ? max : currentFee);
      }
      return Number(
        currentFee <= min ? min : currentFee >= max ? max : currentFee
      );
    },
    /**
     *
     * 佣金及费用（估算）
     * params {number} price  成交价
     * params {number} num    成交数量=成交股数
     * params {string} marker 当前股的市场
     * params {object} List   当前市场佣金的值
     * params {object} close  当前市场卖出佣金的值
     * 仅计算买入，不计算卖出,完整计算在index_dialog.vue页面
     * **/
    brokerageList(price, num, market, List, Close) {
      price = Number(price);
      num = Number(num);
      if (price == 0 || num == 0) {
        this.brokerage = 0;
        return false;
      }
      /**
       *
       *{number} TradVal       交易市值 = 成交价 * 成交股数
       *{number} TradComm       交易佣金：0.029%*交易市值     （交易市值=成交价*成交数量）
       *{number} PlatformFee    平台费：18港币 /一笔订单
       *{number} TradFee        交易费：0.005%*交易市值+0.5港币
       *{number} TradPayment    结算交收费：0.002%*交易市值（最低2港币，最高100港币）
       *{number} TradLevy       交易征费：0.0027%*交易市值  （最低0.01港币）
       *{number} StampDuty      印花税：0.1%*交易市值（不足1港币当作1港币计算，向上取整）
       *
       * **/
      // 港股佣金
      if (market.toLowerCase() == "hkex") {
        let TradVal,
          TradComm,
          TradFee,
          TradPayment,
          TradLevy,
          StampDuty,
          PlatformFee,
          LombardRate;
        TradVal = price * num;
        TradComm = this.maxmin(
          TradVal,
          List.commission,
          List.commission_,
          List._commission
        );
        TradFee = this.maxmin(
          TradVal,
          List.tradeFee,
          List.tradeFee_,
          List._tradeFee
        );
        TradPayment = this.maxmin(
          TradVal,
          List.settlement,
          List.settlement_,
          List._settlement
        );
        TradLevy = this.maxmin(
          TradVal,
          List.tradeLevy,
          List.tradeLevy_,
          List._tradeLevy
        );
        StampDuty = this.maxmin(
          TradVal,
          List.stampDuty,
          List.stampDuty_,
          List._stampDuty,
          true
        );
        PlatformFee = Number(List.platformFee);
        this.brokerage =
          Number(
            TradComm +
              TradFee +
              TradPayment +
              TradLevy +
              StampDuty +
              PlatformFee
          ) + 0.5;
        console.log(
          TradComm,
          TradFee,
          TradPayment,
          TradLevy,
          StampDuty,
          PlatformFee,
          this.brokerage,
          "sd"
        );
        if (this.commissionForm.type == 2) {
          LombardRate = this.maxmin(
            TradVal,
            List.lombardRate,
            List.lombardRate_,
            List._lombardRate,
            false,
            true
          );
          this.brokerage = this.brokerage + Number(LombardRate);
        }
        this.brokerage = Math.round(this.brokerage * 100) / 100;
      } else if (market.toLowerCase() == "us") {
        let MtradComm,
          MTradVal,
          MtradPatment,
          MPlatformFee,
          MSFCFees = 0,
          MtransFee = 0,
          MLombardRate;
        // MADR;
        /**
         *
         *{number}    MtradComm        交易佣金：$0.0039*交易股数，最低$0.99/单
         *{number}    MtradPatment        交收费：$0.00396*成交股数，，最低$0.99/单
         *{number}    MPlatformFee        平台费：$0.004*交易股数，最低$1/订单
         *{number}    MSFCFees       证监会规费【仅卖出收取】：$0.0000221*交易金额（最低$0.01）
         *{number}    MtransFee        交易活动费【仅卖出收取】：$0.000119*卖出数量，（最低$0.01，最高$5.95）
         *{number}    MADR        ADR（美国预托证券）：每股$0.01-0.03之间 (后台设置)
         *
         * **/
        // MtradComm = Number(
        //   List.commission * num <= List._commission
        //     ? List._commission
        //     : List.commission * num >= List.commission_
        //     ? List.commission_
        //     : List.commission * num
        // );
        MtradComm = this.maxmin(
          num,
          List.commission,
          List.commission_,
          List._commission
        );
        // MtradPatment = Number(
        //   List.paymentFee * num <= List._paymentFee
        //     ? List._paymentFee
        //     : List.paymentFee * num >= List.paymentFee_
        //     ? List.paymentFee_
        //     : List.paymentFee * num
        // );
        MtradPatment = this.maxmin(
          num,
          List.paymentFee,
          List.paymentFee_,
          List._paymentFee
        );
        // MPlatformFee = Number(
        //   List.platformFee * num <= List._platformFee
        //     ? List._platformFee
        //     : List.platformFee * num >= List.platformFee_
        //     ? List.platformFee_
        //     : List.platformFee * num
        // );
        MPlatformFee = this.maxmin(
          num,
          List.platformFee,
          List.platformFee_,
          List._platformFee
        );
        this.brokerage =
          MtradComm + MtradPatment + MPlatformFee + MSFCFees + MtransFee;
        if (this.commissionForm.type == 2) {
          MTradVal = price * num;
          MLombardRate = this.maxmin(
            MTradVal,
            List.lombardRate,
            List.lombardRate_,
            List._lombardRate,
            false,
            true
          );
          this.brokerage = this.brokerage + Number(MLombardRate);
        }
        this.brokerage = Math.round(this.brokerage * 100) / 100;
        console.log(
          this.brokerage,
          MtradComm,
          MtradPatment,
          MPlatformFee,
          MSFCFees,
          MtransFee,
          MLombardRate
        );
      } else {
        /**
         * A股通佣金计算
         *{number}    CNtradComm        交易佣金：0.00029*交易股数，最低5/单    
         *{number}    CNPlatformFee        平台费：15元/笔【平台】
      
         *{number}    CNHandel       经手费：0.00487%×成交金额，最低0.01元 【上交所/深交所】
         *{number}    CNManage       证管费：0.002%×成交金额，最低0.01元【中国证监会】
         *{number}    CNStampDuty       印花税【仅卖单收取】：0.1%×成交金额【国家税务总局】需向上取整
         *{number}    CNTransFee       过户费：0.002%×成交金额，最低0.01元【中国结算_上海/中国结算_深圳】
         *{number}    CNTransFee1       登记过户费：0.002%×成交金额，最低0.01元【香港结算】
         *
         * **/
        let CNTradVal,
          CNtradComm,
          CNManage,
          CNPlatformFee,
          CNHandel,
          CNStampDuty,
          CNTransFee,
          CNTransFee1,
          CNLombardRate;
        CNTradVal = Number(price * num);
        CNtradComm = Number(
          this.maxmin(
            CNTradVal,
            List.commission,
            List.commission_,
            List._commission
          )
        );
        CNPlatformFee = Number(List.platformFee);
        // 经手费
        CNHandel = this.maxmin(
          CNTradVal,
          List.handlingFee,
          List.handlingFee_,
          List._handlingFee
        );
        // 证管费
        CNManage = this.maxmin(
          CNTradVal,
          List.certificationFee,
          List.certificationFee_,
          List._certificationFee
        );
        // 过户费
        CNTransFee = this.maxmin(
          CNTradVal,
          List.transferFee,
          List.transferFee_,
          List._transferFee
        );
        // 登记过户费
        CNTransFee1 = this.maxmin(
          CNTradVal,
          List.registerTransferFee,
          List.registerTransferFee_,
          List._registerTransferFee
        );
        this.brokerage = Number(
          CNtradComm +
            CNHandel +
            CNManage +
            CNTransFee +
            CNTransFee1 +
            CNPlatformFee
        );
        if (this.commissionForm.type == 2) {
          CNLombardRate = this.maxmin(
            CNTradVal,
            List.lombardRate,
            List.lombardRate_,
            List._lombardRate,
            false,
            true
          );
          this.brokerage = this.brokerage + Number(CNLombardRate);
        }
        this.brokerage = Math.round(this.brokerage*100)/100;
      }
    },
  },
  computed: {
    stockInfo() {
      return this.$store.state.index.stockInfo;
    },
  },
};
</script>
<style lang="less">
.commission_cal {
  width: 340px;
  margin: 0 auto;
  .current_commission {
    display: flex;
    justify-content: center;
    // align-items: center;
    color: @fff;
    .commissionPrice {
      font-size: 30px;
      padding-left: 48px;
    }
    .commissionUnit {
      padding-left: 10px;
      font-size: 14px;
      line-height: 76px;
    }
  }
}
.form_cal {
  .el-form-item__label {
    font-size: 12px;
    color: @fff;
    text-align: start;
  }
  .el-form-item__content {
    .el-input {
      .el-input__inner {
        height: 30px;
        background-color: @LightBorderLine;
        border: none;
        font-size: 12px;
        color: @fff;
      }
    }
    .el-input-number {
      width: 100%;
      line-height: 28px;
      .el-input-number__decrease {
        background-color: @LightBorderLine;
        border-right: 1px solid @deepBg;
      }
      .el-input-number__increase {
        background-color: @LightBorderLine;
        border-left: 1px solid @deepBg;
      }
    }
  }
  .el-radio-group {
    padding-top: 12px;
  }
}
.computed {
  display: flex;
  justify-content: center;
  margin-left: 36px;
  margin-top: 30px;
  margin-bottom: 20px;
}
.search {
  width: 100%;
  .inco_seach {
    height: 22px;
  }
}
</style>